package cn.flying.cloud.task.core.quartz.loadbalance;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

/**
 * 轮询本地负载均衡
 *
 * @author: admin
 * @date: 2025年03月17日 20:29
 * @version: 1.0
 */
@Component
public class RoundLoadBalance implements LoadBalance {

    @Resource
    private DiscoveryClient discoveryClient;
    private AtomicInteger atomicCount = new AtomicInteger(0);

    /**
     * 选择一个服务
     *
     * @param serviceId
     * @return
     */
    @Override
    public ServiceInstance choose(String serviceId) {
        //1.根据服务的名称 获取 该服务集群地址列表
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        //2.判断是否null
        if (instances == null || instances.isEmpty()) {
            return null;
        }
        //3.使用负载均衡算法

        int index = atomicCount.incrementAndGet() % instances.size();// 0+1
        return instances.get(index);
    }
}
